//
// Copyright 2011 ReedRex Corp
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// BookCoverViewController.m
// Cloud BookShelf
//
// Created by Shunichi Takagi on 11/02/25.
//

#import "BookCoverViewController.h"


@implementation BookCoverViewController

@synthesize bookService;
@synthesize book;

- (id) initWithBook:(Book *)aBook andService:(BookService *)aBookService {
	self.book = aBook;
	self.bookService = aBookService;
	
	return self;
}


// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
	[super loadView];
	
	self.title = book.title;
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"表紙を変更"
																			   style:UIBarButtonItemStylePlain
																			  target:self
																			  action:@selector(changeCover)] autorelease];
}

- (void) changeCover {
	UIImagePickerController *picker = [[UIImagePickerController alloc] init];
	picker.delegate = self;
	picker.sourceType = UIImagePickerControllerSourceTypeCamera;
	
	[self presentModalViewController:picker animated:YES];
	
	[picker release];
}

- (void) imagePickerController:(UIImagePickerController*)picker  
		 didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary*)editingInfo { 

	CGRect frameSize = self.view.frame;
	CGSize newSize = CGSizeMake(frameSize.size.width/2, frameSize.size.height/2);
	
	UIGraphicsBeginImageContext(newSize);
	[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
	UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	
	[bookService storeImage:newImage with:self.book];
		
    [picker dismissModalViewControllerAnimated:YES];
}

- (void) viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	
	UIImage *image = [bookService fetchImage:book];
	UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
	imageView.contentMode = UIViewContentModeScaleAspectFit;
	
	self.view = imageView;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
